Advent of Code 2020: Day 1

Part of the series Advent of Code 2020 (0 posts total).

Day 1 is usually the easiest challenge in Advent of Code. This year was no different. For each challenge there is a story, but I’ll look past that for conciseness. Given a series of numbers we must find the two numbers which sum to $2020$ and multiplying them to get the answer to part 1. For part 2, we must find three numbers that sum to $2020$ and multiply them for the answer.

In the first part, I merely do two for-loops across the same list and compare, breaking when the numbers are found. For part 2, in the same for-loops, I compute $2020$ minus the two numbers, and if that number is in the list of numbers, we have found our three magic numbers. The code looks like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
with open("input/day01.txt") as file:
    expenses = sorted(list(map(int, file.readlines())))

for e1 in expenses:
    for e2 in expenses:
        if e1 == e2 or e1 + e2 > 2020:
            break
        if e1 + e2 == 2020:
            part1 = e1 * e2
        # Checking if third operand can be found to sum to 2020
        e3 = 2020 - (e1 + e2)
        if e3 in expenses:
            part2 = e1 * e2 * e3

The first two lines are reading the file and converting the read characters to integers. It is important that this is sorted, as this ensures that we will find the answer to part two before part 1. Naturally, three numbers summing to $2020$ must be earlier in the for-loops than two numbers summing to $2020$. The


The full code for this day can be found here. The entire repository is available at GitHub.

Published 26. August 2022

Last modified 29. August 2022